package com.ctg.itrdc.sysmgr.portal.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

import com.ctg.itrdc.pasp.context.service.BaseService;
import com.ctg.itrdc.sysmgr.portal.api.dto.OrganizationDTO;
import com.ctg.itrdc.sysmgr.portal.api.service.IOrganizationService;
import com.ctg.itrdc.sysmgr.portal.data.IOrgPostRelDao;
import com.ctg.itrdc.sysmgr.portal.data.IOrganizationDao;
import com.ctg.itrdc.sysmgr.portal.data.IStaffDao;
import com.ctg.itrdc.sysmgr.portal.data.IStaffOrgRelDao;
import com.ctg.itrdc.sysmgr.portal.data.ISystemPostDao;
import com.ctg.itrdc.sysmgr.portal.data.entity.OrgPostRel;
import com.ctg.itrdc.sysmgr.portal.data.entity.Organization;
import com.ctg.itrdc.sysmgr.portal.data.entity.Staff;
import com.ctg.itrdc.sysmgr.portal.data.entity.StaffOrgRel;
import com.ctg.itrdc.sysmgr.portal.data.entity.SystemPost;
import com.ctg.itrdc.sysmgr.portal.data.vo.OrganizationVO;
import com.ctg.itrdc.sysmgr.portal.service.exception.SysmgrServiceException;
import com.ctg.itrdc.sysmgr.portal.service.utils.BeanUtils;
import com.google.common.collect.Lists;

@Component("organizationService")
public class OrganizationServiceImpl extends BaseService<Organization, Long, OrganizationDTO> implements IOrganizationService {

	@Resource
	private IOrganizationDao organizationDao;
	@Resource
    private IOrgPostRelDao orgPostRelDao;
	@Resource
	private ISystemPostDao systemPostDao;

	@Resource
	private IStaffOrgRelDao staffOrgRelDao;
	@Resource
	private IStaffDao staffDao;
	
	@Override
	public Long insert(OrganizationDTO dto){
		OrganizationDTO tmp  = new OrganizationDTO();
		tmp.setOrgName(dto.getOrgName());
		tmp.setParentOrgId(dto.getParentOrgId());
		if(exists(tmp)){
			throw new SysmgrServiceException("同父级，子组织不能同名！");
		}
		try {
			long i = super.insert(dto);
			//去掉 机构编号自动生成的逻辑 xkw 20160808
//		OrganizationDTO tmp2  = new OrganizationDTO();
//		tmp2.setId(i);
//		tmp2.setOrgCode(RandomCodeUtil.gen(RandomCodeUtil.SYSTEM_ORG, i));
//		sysmgrBaseService.updateNotNullFieldsByPrimaryKey(tmp2);
			return  i;
		} catch (DuplicateKeyException e) {
			throw new SysmgrServiceException("机构编码重复");
		}
	}
	
	@Override
	public int updateByPrimaryKey(OrganizationDTO dto) {
		try {
			return super.updateByPrimaryKey(dto);
		} catch (DuplicateKeyException e) {
			throw new SysmgrServiceException("机构编码重复");
		}
	}

	@Override
	public List<OrganizationDTO> selectSubOrg(OrganizationDTO dto){
//		List<Long> orgIdList = orgPostRelDao.selectOrgIdByPostId(sysPostId);
//		if(CollectionUtils.isNotEmpty(orgIdList)){
		Organization organization = BeanUtils.applyIfNotException(dto, Organization.class);
		// 搜索时，递归获取所有id TODO 待优化
		List<Long> orgIds = Lists.newArrayList();
		if(organization.getOrgId()!=null && StringUtils.isNotBlank(organization.getOrgName())){ 
			List<OrganizationDTO> orgList = selectMainAndSubByOrgId(organization.getOrgId());
			for (int i = 0; i < orgList.size(); i++) {
				orgIds.add(orgList.get(i).getOrgId());
			}
		}
		List<OrganizationVO> entityList = organizationDao.selectSub(organization,orgIds);
		return BeanUtils.copyListNotException(entityList, OrganizationDTO.class);
//		}
//		return null;
	}
	
	
//	@Override
//	public List<OrganizationDTO> searchOrgTree(Long sysPostId,OrganizationDTO dto){
//		List<OrganizationDTO> orgList = selectSubOrg(sysPostId, dto);
//		HashSet<OrganizationDTO> orgSet = Sets.newHashSet(orgList);
//		List<OrganizationDTO> tmpList = BeanUtils.copyListNotException(orgList, OrganizationDTO.class);
//		for (OrganizationDTO org : tmpList) {
//			Long parentOrgId = org.getParentOrgId();
//			if(parentOrgId!=null){
//				// 先找到上一级
//				OrganizationDTO tmp = new OrganizationDTO();
//				tmp.setOrgId(parentOrgId);
//				tmp = this.selectByPrimaryKey(tmp); // TODO 没把sysPostId作为条件查询，可能存在bug。
//				// 递归获取上一级的上一级的子集
//				selectParent(sysPostId, tmp, orgSet); 
//			}
//		}
//		return selectOrgTree(Lists.newArrayList(orgSet));
//	}
	
//	/*
//	 * 寻找父节点
//	 */
//	public void selectParent(Long sysPostId,OrganizationDTO sub,Set<OrganizationDTO> resultList){
//		
//		if(sub == null ) return ;
//		
//		if(sub.getParentOrgId()!=null && sub.getParentOrgId()!=0){
//			OrganizationDTO tmp = new OrganizationDTO();
//			tmp.setParentOrgId(sub.getParentOrgId()); 
//			List<OrganizationDTO> subList = selectSubOrg(sysPostId,tmp);
//			if(subList!=null) {
//				resultList.addAll(subList); // 添加所有子
//			}
//			OrganizationDTO parent = new OrganizationDTO();
//			parent.setOrgId(sub.getParentOrgId());
//			parent = this.selectByPrimaryKey(parent); // TODO 没把sysPostId作为条件查询，可能存在bug。
//			selectParent(sysPostId, parent, resultList);
//		}else{
//			resultList.add(sub); // 顶级添加进来
//		}
//		
//	}
	
//	@Override
//	public List<OrganizationDTO> selectOrgTree(Long sysPostId){
//		List<OrganizationDTO> dtoList = selectBySysPostId(sysPostId);
//		if(CollectionUtils.isNotEmpty(dtoList)){
//			return selectOrgTree(dtoList);
//		}
//		return null;
//	}
//	
//	@Override
//	public List<OrganizationDTO> selectBySysPostId(Long sysPostId){
//		List<Long> orgIdList = orgPostRelDao.selectOrgIdByPostId(sysPostId);
//		if(CollectionUtils.isNotEmpty(orgIdList)){
//			List<Organization> entityList = organizationDao.selectByIdList(orgIdList);
//			List<OrganizationDTO> dtoList = BeanUtils.copyListNotException(entityList, OrganizationDTO.class);
//			return dtoList;
//		}
//		return null;
//	}
	
	@Override
	public List<OrganizationDTO> selectMainAndSubByOrgId(Long orgId){
		
		List<Organization> entityList = Lists.newArrayList();
		
		Organization entity = new Organization();
		entity.setOrgId(orgId);
		Organization main = organizationDao.selectByPrimaryKey(entity);
		if(main!=null){
			entityList.add(main);
			selectSubOrg(main,entityList);
		}
		if(CollectionUtils.isEmpty(entityList)){
			return null;
		}
		return BeanUtils.copyListNotException(entityList, OrganizationDTO.class);
		
	}
	
	private void selectSubOrg(Organization main,List<Organization> entityList){
		Organization entity = new Organization();
		entity.setParentOrgId(main.getOrgId());
		List<Organization> subList = organizationDao.selectByExample(entity);
		entityList.addAll(subList);
		for (Organization organization : subList) {
			selectSubOrg(organization,entityList);
		}
	}


	@Override
	public int deleteByPrimaryKey(OrganizationDTO dto) {
		OrganizationDTO organizationDTO = new OrganizationDTO();
		Long orgId = dto.getOrgId();
		organizationDTO.setParentOrgId(orgId);
		List<?> children = this.selectByExample(organizationDTO);
		if(CollectionUtils.isNotEmpty(children)){
			throw new SysmgrServiceException("请先删除组织的下属组织");
		}
		
		OrgPostRel OrgPostRel = new OrgPostRel();
		OrgPostRel.setOrgId(orgId);
		SystemPost sysPost = new SystemPost();
		sysPost.setOrgId(orgId);
		List<SystemPost> sysPosts = systemPostDao.selectByExample(sysPost);
		List<OrgPostRel> orgPostRel = orgPostRelDao.selectByExample(OrgPostRel);
		if(CollectionUtils.isNotEmpty(orgPostRel) || CollectionUtils.isNotEmpty(sysPosts)){
			throw new SysmgrServiceException("请先删除所属组织的岗位");
		}
		
		StaffOrgRel staffOrgRel = new StaffOrgRel();
		Staff staff = new Staff();
		staffOrgRel.setOrgId(orgId);
		staff.setOrgId(orgId);
		List<StaffOrgRel> staffOrg = staffOrgRelDao.selectByExample(staffOrgRel);
		List<Staff> staffs = staffDao.selectByExample(staff);
		if(CollectionUtils.isNotEmpty(staffOrg) || CollectionUtils.isNotEmpty(staffs)){
			throw new SysmgrServiceException("请先删除所属组织的员工");
		}
		
		return super.deleteByPrimaryKey(dto);
	}

	@Override
	public int[] batchDeleteByPrimaryKey(List<OrganizationDTO> dtoList) {
		List<Organization> entities = BeanUtils.copyListNotException(dtoList, Organization.class);
		return organizationDao.jdbcBatchDeleteByPrimary(entities);
	}

//	/**
//	 * 获取菜单树
//	 * 
//	 * @param dtoList
//	 * @return
//	 */
//	private List<OrganizationDTO> selectOrgTree(List<OrganizationDTO> dtoList) {
//		List<OrganizationDTO> result = new ArrayList<>();
//		for (OrganizationDTO main : dtoList) {
//			if (main.getParentOrgId() == null || main.getParentOrgId() == 0) {
//				selectSubOrg(main, dtoList);
//				result.add(main);
//			}
//		}
//		return result;
//	}
//
//	/**
//	 * 获取子菜单
//	 * 
//	 * @param main
//	 * @param dtoList
//	 */
//	private void selectSubOrg(OrganizationDTO main, List<OrganizationDTO> dtoList) {
//		List<OrganizationDTO> item = new ArrayList<>();
//		for (OrganizationDTO sub : dtoList) {
//			Long parentOrgId = sub.getParentOrgId()==null?null:sub.getParentOrgId().longValue();
//			if (parentOrgId == main.getOrgId()) {
//				selectSubOrg(sub, dtoList); // 递归获取
//				item.add(sub);
//			}
//		}
//		if(item.size()>0)
//			main.setItem(item);
//	}


}
